import "./plugins/fundebug"
import base64 from "./utils/base64.min"
import API, { request } from "./plugins/api"
import { config } from "./config"
import {handleUrlParams, requestSubscribeMessage} from "./utils/util"
// 全局挂载API
const injectGlobal = () => {
	wx.$API = API
}
//白名单，处于白名单中的页面不校验登录验证
const whiteListReg = [
	/^informationVerification\//,
	/marketing\/pages\/driveTraffic\/*/,
	/^pages\/login\/noLoginRequiredZone\/index$/,
	/^pages\/picture\/index$/,
	/^pages\/login\/index$/,
]
//登录页面地址
let loginPage = config.loginPage
App({
	afterLoginCallbackList: [], //登录之后执行的钩子
	onLaunch(options) {
		//for debug
		// const accountInfo = wx.getAccountInfoSync();
		// const envVersion = accountInfo.miniProgram.envVersion;
		// if (envVersion === 'develop' || envVersion === "trail") {
		// 	const url = handleUrlParams("/pages/picture/index", {
		// 		srcList: encodeURIComponent(
		// 			JSON.stringify([
		// 				"https://xwx.gzzmedu.com/pic/wx-x-mai/1_b5e535ad86b648ea870375de7c0a879.png",
		// 				"https://xwx.gzzmedu.com/pic/wx-x-mai/2_6e2fe813ea69baa69b42f82236655ca.png",
		// 			]),
		// 		),
		// 	})
		// 	console.log(url)
		// 	setTimeout(()=>{
		// 		wx.navigateTo({
		// 			url: url,
		// 		})
		// 	},3000)
		// }

		// 记录重定向地址
		this.getDedirect(options)
		// 注入全局变量
		injectGlobal()
		// 检查小程序更新
		this.checkUpdate()
		// 检测网络状态
		wx.onNetworkStatusChange((res) => {
			this.globalData.isConnected = res.isConnected
		})
		this.globalData.isHzdb = false
	},
	onShow(options) {
		// wx.login({
		// success: (obj) => {
		//   console.log(obj.code, 'code')
		// },
		// })

		// 获取用户订阅的消息推送模板并传给后台
		requestSubscribeMessage(this)

		// 订阅消息模板点击率统计
		if (options.query && options.query.publishDetailId) {
			console.log("订阅消息模板点击率统计", options.query.publishDetailId)
			request({
				url: "api/user/wxNoticeClick",
				method: "POST",
				data: {
					publishDetailId: options.query.publishDetailId,
				},
			}).catch((err) => {
				console.log(err, "err")
			})

			// const sendNotificationClick = () => {
			// 	console.log("订阅消息模板点击率统计", options.query.notificationId);
			// 	request({
			// 		url: "api/user/wxNoticeClick",
			// 		method: "POST",
			// 		data: {
			// 			notificationId: options.query.notificationId,
			// 		},
			// 	}).catch((err) => {
			// 		console.log(err, "err")
			// 	})
			// }
			// // 判断是否有登录
			// console.log(wx.getStorageSync("token"), "token");
			// if (wx.getStorageSync("token")) {
			// 	sendNotificationClick()
			// } else {
			// 	// 添加钩子，登录之后执行
			// 	this.afterLoginCallbackList.push(sendNotificationClick)
			// }
		}

		// 记录重定向地址
		this.getDedirect(options)
		// 获取参数
		const { path, scene, query, referrerInfo } = options
		this.globalData.enterPath = path
		this.globalData.app = query.app
		if (this.globalData.from !== "end") {
			this.globalData.from = query.from
		}
		if (query.at && scene !== 1038) {
			this.globalData.actionType = query.at
		}
		// 从app分享卡片、单人聊天框、群聊天框进入
		console.log(scene, "当前场景值", options)
		this.globalData.enterPage = path
		this.test()
		if (scene === 1154) {
			return
		}
		if (scene === 1065) {
			// this.globalData.dlhsdxCode = query.dlhsdxCode
			// this.globalData.InstitutionCode = query.InstitutionCode
			wx.setStorage({ key: "dlhsdxCode", data: query.dlhsdxCode })
			wx.setStorage({ key: "InstitutionCode", data: query.schoolCode })
			return
		}
		if (scene === 1036 || scene === 1007 || scene === 1008) {
			// 如果是真伪验证界面，就不需要验证登录
			if (path === "pages/workService/authenticityVerification/index") {
				return
			}
		}
		if (this.globalData.from === "xAdzkjdx") {
			wx.navigateTo({
				url: "/pages/xAdzkjdx/index",
			})
			return
		} else if (this.globalData.from === "WZXY" && query.app === "file") {
			console.log("这是在app.js页面 从我在校园跳转过来 进入 文件代办", query)
		} else if (this.globalData.from === "dlwgy") {
			this.globalData.corpCode = query.js_code
			this.globalData.corpId = query.qy_appid
			console.log(this.globalData, "this.globalData")
		}
		if (query.scene) {
			console.log("扫码跳转带的参数", query.scene)
			// 跳转活动页面参数 type:string  a=xxx&b=xxx
			let paseBefore = decodeURIComponent(query.scene)
			const { a, t, u, sid } = this.parseScene(paseBefore)

			// 印之梦小程序
			if (sid) {
				this.globalData.YZM.sid = sid
				console.log(sid, "获取印之梦打印机")
			}

			if (t) {
				this.globalData.activityData.id = a
				this.globalData.activityData.captainId = u
				this.globalData.redirect = `/${path}?scene=${query.scene}`
				this.globalData.activityData.isCollect = 1
				console.log(
					"现在是跳转活动页面,参数为:",
					{ a, t, u, path },
					"重定向路径为:" + this.globalData.redirect,
				)
			}
		}

		this.globalData.extraData = referrerInfo.extraData
		if (referrerInfo.extraData && this.globalData.extraData.origin === "YZM") {
			console.log("现在是由 印之梦 小程序带参跳转")
		}

		//信息核验
		//检查页面路径是否在白名单中
		let isWhiteList = false
		for (let i = 0; i < whiteListReg.length; i++) {
			if (whiteListReg[i].test(path)) {
				isWhiteList = true
				break
			}
		}
		if (isWhiteList) {
			console.log("当前页面在白名单中，不校验登录")
			return
		}

		// 登录校验
		this.loginVerify(referrerInfo)
	},

	onHide() {
		this.globalData.autoQyLogin = true
	},
	/**
	 * @see 测试方法,书写测试开发代码
	 */
	test() {
		// wx.login({
		//   success: (res) => {
		//     const request = {
		//       jsCode: res.code
		//     }
		//     if (wx.qy) {
		//       wx.qy.login({
		//         success: (res) => {
		//           request.qyCode = res.code
		//           console.log('企业微信code', request)
		//           wx.$API['login/testCode'](request)
		//         }
		//       })
		//     }
		//   }
		// })
	},
	/**
	 * @see 获取并记录重定向地址
	 */
	getDedirect(options) {
		const { query } = options
		const { redirect } = query
		// 记录重定向地址
		if (redirect) {
			this.globalData.redirect = redirect
		}
	},

	/**
	 * @see 储存token、userInfo、schoolConfig
	 * @param {token} String
	 * @param {userInfo} Object
	 * @param {schoolConfig} Object
	 */
	storageData(token, userInfo, schoolConfig, code) {
		wx.setStorage({ key: "token", data: token })
		wx.setStorage({ key: "userInfo", data: userInfo })
		wx.setStorage({ key: "schoolConfig", data: schoolConfig })
		this.globalData.userId = wx.getStorageSync("userInfo").userId
		wx.setStorage({ key: "code", data: code })
		// wx.setStorageSync('token', token)
		// wx.setStorageSync('userInfo', userInfo)
		// wx.setStorageSync('schoolConfig', schoolConfig)
	},
	/**
	 * @see token校验
	 * @param {token} String
	 */
	tokenVerify(token) {
		try {
			const tokenPlyload = base64.decode(token.split(".")[1])
			const tokenJson = JSON.parse(tokenPlyload)
			const currentTime = new Date().getTime()
			let { exp } = tokenJson
			exp = parseInt(exp + "000")
			if (exp - currentTime > 60 * 1000 * 50) {
				// if (exp - currentTime > 86400000 * 5) {
				// 86400000 * 5
				// token未过期（86400000为1天的时间戳，这个判断为每两天一刷）
				this.globalData.userId = wx.getStorageSync("userInfo").userId
				this.againLogin({
					bool: this.globalData.enterPage === loginPage,
				})
				wx.hideLoading()
			} else {
				console.log("token已过期")
				// token已过期
				wx.setStorage({ key: "token", data: "" })
				this.againLogin()
			}
		} catch (error) {
			wx.hideLoading()
			wx.showModal({
				title: "提示",
				content: "登录异常",
				showCancel: false,
			})
			wx.clearStorageSync()
			console.log("token错误", error, token)
		}
	},
	/**
	 * @see 重新登录
	 */
	againLogin({ bool } = {}) {
		return new Promise((resolve, reject)=>{
			if (this.globalData.isHzdb) {
				reject()
				return
			}
			// wx.showLoading({ mask: true, title: "登录中~" })
			wx.login({
				success: (res) => {
					const request = { 
						code: res.code, 
						loginType: 1 
					}
					console.log("访问登录接口", request)
					API["login/login"](
						request,
						{
							unAuth: true
						}
					)
						.then((result) => {
							const { token, data, schoolConfig } = result
							this.storageData(token, data[0], schoolConfig)
							// wx.hideLoading()
							if (
								this.afterLoginCallbackList &&
								this.afterLoginCallbackList.length > 0
							) {
								console.log("登录之后钩子")
								this.afterLoginCallbackList.forEach((item) => {
									item()
								})
								this.afterLoginCallbackList = []
							} else {
								if (!this.globalData.redirect && bool) {
									this.globalData.enterPage = ""
									wx.reLaunch({
										url: "/pages/home/index",
									})
								}
							}
							resolve()
						})
						.catch((err) => {
							// wx.hideLoading()
							if (!this.globalData.isHzdb) {
								console.log("用户尚未登录，将跳转到登录页面")
								if (err === "-3001" && this.globalData.enterPath !== loginPage) {
									// 用户没有绑定过微信
									wx.reLaunch({
										url: loginPage,
									})
								} else {
									// 后端改状态麻烦,这里改判断汉字,如果报错,请第一时间排除此处
									if (err === "该学校暂未开放") {
										wx.showModal({
											title: "提示",
											content: err,
											showCancel: false,
											complete: (msg) => {
												wx.reLaunch({
													url: loginPage,
												})
											},
										})
									}
									console.log("login/checkLogin", err)
								}
							}
							reject()
						})
				},
				fail: (err) => {
					// wx.hideLoading()
					wx.showModal({
						title: "提示",
						content: "获取code失败,请退出微信后重试",
						showCancel: false,
					})
					reject()
				},
			})
		})
	},
	/**
	 * @see 登录校验
	 */
	loginVerify() {
		console.log("登录校验")
		const token = wx.getStorageSync("token")
		if (token) {
			// 效验token是否过期
			this.tokenVerify(token)
		} else {
			// 重新登录
			this.againLogin()
		}
	},
	/**
	 * @see 获取推送模板ID
	 */
	getTemplateIds(schoolCode = null) {
		let request
		if (schoolCode) {
			request = { schoolCode }
		} else {
			request = {}
		}
		API["home/getTemplateIds"](request)
			.then((result) => {
				const { data } = result
				this.globalData.tmplIds = data
			})
			.catch((err) => {
				console.log("home/getTemplateIds", err)
			})
	},
	/**
	 * @see 解析scene参数,接收参数格式为  a=xxx&b=xxx  返回{a:xxx,b:xxx}
	 */
	parseScene(scene) {
		let str = scene.split("&")
		let obj = {}
		str.forEach((item) => {
			let arr = item.split("=")
			obj[arr[0]] = arr[1]
		})
		return obj
	},
	/**
	 * @see 检查更新小程序
	 */
	checkUpdate() {
		const updateManager = wx.getUpdateManager()
		// 在分享朋友圈单页模式中,暂时没有getUpdateManager,返回值为undefined
		if (updateManager) {
			updateManager.onCheckForUpdate((result) => {
				if (result.hasUpdate) {
					updateManager.onUpdateReady(() => {
						wx.showModal({
							title: "更新提示",
							content: "新版本已经上线啦~",
							confirmText: "立即体验",
							showCancel: false,
							success: (result) => {
								updateManager.applyUpdate()
							},
						})
					})
					updateManager.onUpdateFailed(() => {
						wx.showModal({
							title: "有新版本了哟",
							content: "新版本已经上线啦，重启微信再进入体验~",
							showCancel: false,
						})
					})
				}
			})
		}
	},
	/**
	 * @see 判断当前环境是不是企业微信
	 */
	surroundings() {
		return new Promise((resolve, reject) => {
			wx.getSystemInfo({
				success(res) {
					if (res.environment === "wxwork") {
						resolve(res)
					} else {
						reject("当前环境为微信客户端")
					}
				},
			})
		})
	},
	openZlzp(key) {
		let schoolConfig = wx.getStorageSync("schoolConfig")
		wx.navigateToMiniProgram({
			appId: "wx08e25a163d60852c",
			path: this.globalData.zlMapForm[schoolConfig.schoolCode][key],
		})
	},
	globalData: {
		zlMapForm: {
			// 智联招聘对照表
			4000011111: {
				// 正脉微校 测试 使用的内容是  广州华商学院
				jlmb: "/packageResume/activityNineResume/activityNineResume?activityShareId=5303&utm_source=9resume", // 简历模板
				cp: "/packageResume/activityNineResume/activityNineResume?activityShareId=5352&utm_source=9resume", // 测评
				kc: "/packageResume/activityNineResume/activityNineResume?activityShareId=5353&utm_source=9resume", // 课程
				zwy: "/packageResume/activityNineResume/activityNineResume?activityShareId=5568&utm_source=9resume", // 职位页
			},
			4144012621: {
				// 广州华商
				jlmb: "/packageResume/activityNineResume/activityNineResume?activityShareId=5303&utm_source=9resume", // 简历模板
				cp: "/packageResume/activityNineResume/activityNineResume?activityShareId=5352&utm_source=9resume", // 测评
				kc: "/packageResume/activityNineResume/activityNineResume?activityShareId=5353&utm_source=9resume", // 课程
				zwy: "/packageResume/activityNineResume/activityNineResume?activityShareId=5568&utm_source=9resume", // 职位页
			},
			4144011078: {
				// 广州大学
				jlmb: "/packageResume/activityNineResume/activityNineResume?activityShareId=5378&utm_source=9resume", // 简历模板
				cp: "/packageResume/activityNineResume/activityNineResume?activityShareId=5379&utm_source=9resume", // 测评
				kc: "/packageResume/activityNineResume/activityNineResume?activityShareId=5380&utm_source=9resume", // 课程
				zwy: "/packageResume/activityNineResume/activityNineResume?activityShareId=5549&utm_source=9resume", // 职位页
			},
			4144010578: {
				// 韩山师范学院
				jlmb: "/packageResume/activityNineResume/activityNineResume?activityShareId=5386&utm_source=9resume", // 简历模板
				cp: "/packageResume/activityNineResume/activityNineResume?activityShareId=5387&utm_source=9resume", // 测评
				kc: "/packageResume/activityNineResume/activityNineResume?activityShareId=5388&utm_source=9resume", // 课程
				zwy: "/packageResume/activityNineResume/activityNineResume?activityShareId=5570&utm_source=9resume", // 职位页
			},
		},
		isHzdb: false, // 是否在互助代办页面里面,以免app onshow强制退回到登录页
		YZM: {
			sid: "",
		},
		corpCode: "",
		corpId: "",
		enterPath: "",
		actionType: "",
		enterPage: "",
		isConnected: true,
		redirect: "",
		userId: "",
		tmplIds: [],
		extraData: null, // 别的小程序跳转我们小程序时带过来的id
		autoQyLogin: true, // 是否触发企业微信自动登录
		from: "", // 从哪儿跳转过来 tp/订阅消息
		app: "", // 去哪个应用
		mask: {
			phone: "",
			schoolName: "",
			studentId: "",
			applicationNumber: 0,
		},
		activityData: {
			activityId: "", // 活动id
			avatar: "", // 用户头像
			id: "", // 数字活动id
			isCollect: "", //
			captainId: "", // 队长id
		},
	},
})
